package udpServer

import (
	"fmt"
	"log"
	"net"
	"strconv"
)

const OnStart string = "on_udp_start"
const OnMessage string = "on_udp_message"
const OnConnect string = "on_udp_connect"
const OnDisConnect string = "on_udp_disconnect"
const OnError string = "on_udp_err"
const OnClose string = "on_udp_close"

type UdpServer struct {
	ListenPort int
	EventMap   map[string]interface{}
}

func (server *UdpServer) init() {
	if server.EventMap == nil {
		server.EventMap = make(map[string]interface{})
	}
}
func (server *UdpServer) OnMessage(fun func(data []byte, udpCon *net.UDPConn, addr *net.UDPAddr)) {
	server.init()
	server.EventMap[OnMessage] = fun
}

func (server *UdpServer) Start() error {
	server.init()
	udpConn, err := net.ListenUDP("udp", &net.UDPAddr{
		IP:   net.IPv4(0, 0, 0, 0),
		Port: server.ListenPort,
	})
	if err != nil {
		return err
	}
	fmt.Println("启动udp服务成功:" + strconv.Itoa(server.ListenPort))
	for {
		var data [1024]byte
		n, addr, err := udpConn.ReadFromUDP(data[:])
		fmt.Println("接受到数据")
		if err != nil {
			log.Printf("Read from udp server:%s failed,err:%s", addr, err)
			break
		}
		if fun, ok := server.EventMap[OnMessage]; ok {
			function := fun.(func(data []byte, udpCon *net.UDPConn, addr *net.UDPAddr))
			go function(data[:n], udpConn, addr)
		}
	}
	return err
}
